/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import cs4280.action.CinemaControl;
import cs4280.bean.Member;
import cs4280.dao.MemberDAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.Context;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.sql.DataSource;

/**
 *
 * @author PangPei
 */
public class loginControll extends HttpServlet {

    public static enum RESULT {

        OK, DUPLICATE, FAIL
    };

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {


            String username = request.getParameter("j_username");
            String password = request.getParameter("j_password");

//            Context initCtx = new InitialContext();
//            Context envCtx = (Context) initCtx.lookup("java:comp/env");
//            DataSource ds = (DataSource) envCtx.lookup("jdbc/phonebook");
//            Connection con = ds.getConnection();
//
//            PreparedStatement pstmt = con.prepareStatement("SELECT password FROM [member] WHERE username=?");
//            pstmt.setString(1, username);
//            ResultSet rs = pstmt.executeQuery();
//
//            String prevURL = (String)request.getRequestURI();
//            String return_password = rs.getString("password");


            if (username.equals("yvonne")) {
                request.setAttribute("j_username", "yvonne");
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response);

            }





//        } catch (NamingException e) {
//           out.println("<div style='color: red'>" + e.toString() + "</div>");
//        } catch (SQLException e) {
//           out.println("<div style='color: red'>" + e.toString() + "</div>");
//        }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        String jspPage = this.doIndexPage(request, response);
        this.dispatchJsp(jspPage, request, response);*/
        this.doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jspPage = new String("");

        if ("doauthenticate".equalsIgnoreCase(request.getParameter("todo")) != false) {
            jspPage = this.doAuthenticate(request, response);
        }
        if ("goindex".equalsIgnoreCase(request.getParameter("todo")) != false) {
            jspPage = this.doIndexPage(request, response);
        } else {
            jspPage = this.doLogin(request, response);
        }
        this.dispatchJsp(jspPage, request, response);
    }

    private void dispatchJsp(String jspPage, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(jspPage).forward(request, response);
    }

    public String doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return "/index.jsp";
    }

    public String doIndexPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return "/index.jsp";
    }

    public String doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Member member = new Member();
        HttpSession session = request.getSession();

        MemberDAO memberDAO = new MemberDAO();
        Member currentmember = (Member)session.getAttribute("member");

        member.setPassword(request.getParameter("j_password"));
        member.setUsername(request.getParameter("j_username"));
        //if the member is in the system, jump to user_info

        boolean valid = memberDAO.validateMember(member);
        if (valid == true) {



            member = memberDAO.getMember(request.getParameter("j_username"));
            if (currentmember == null ) {
            session.setAttribute("member", member);
        }
            session.setAttribute("loggedin", true);
            request.setAttribute("member", member);
           request.setAttribute("msg", "Login Successful!");
        } else {
            request.setAttribute("msg", "Wrong password!");
        }
        return CinemaControl.doIndexPage(request, response);
    }
}
